package cn.xuchunh.campusbbs.net;

import org.json.JSONException;
import org.json.JSONObject;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.utils.JsonKey;

/**
 * Created by XuChunH on 2016/3/7.
 */
public abstract class SimpleXJsonListener<T> implements XJsonListener<T> {

    @Override
    public T parseJson(String json) throws Exception {
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.optInt(JsonKey.RS) == 1) {
                return parseData(jsonObject);
            } else {
                JSONObject head = jsonObject.optJSONObject(JsonKey.HEAD);
                throw new Exception(head.optString(JsonKey.ERR_INFO));
            }
        } catch (JSONException ignored) {
            throw new Exception(AppContext.getInstance().getString(R.string.error_parse_json));
        }
    }

    public abstract T parseData(JSONObject jsonObject) throws Exception;
}
